<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/9/29
 * Time: 15:37
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
class Orderps extends Base
{
    protected $t_names = ['','夏季套装','秋季套装','礼服套装','冬季套装','西服套装'];
    /**
     * 订单数据-
     */
    public function index(){
        if(request()->isAjax ()){
            extract(input());
            $map = [];
            $map['is_delete'] = 0;
            $map['order_contract'] = 3;
            $map['is_pay'] = 1;
            if(isset($n_title)&&$n_title!="")
            {
                $map['order_no|order_back_order_id|name|mobile'] = ['like',"%" . $n_title . "%"];
            }
            if(isset($contract)&&$contract!="")
            {
                $map['order_contract'] = $contract;
            }
            if(isset($schoolid)&&$schoolid!="")
            {
                $map['order_school'] = $schoolid;
            }
            if(isset($order_erp_year)&&$order_erp_year!="")
            {
                $map['order_erp_year'] = $order_erp_year;
            }
            if(isset($type) && $type){
                if($type == 2){
                    $map['is_send'] = 0;
                }
                if($type == 3){
                    $map['is_send'] = 1;
                }
                if($type == 4){
                    $map['is_send'] = 2;
                }
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end=="")
            {
                $map['pay_time'] = ['>= time',$start];
            }
            if(isset($end)&&$end!=""&&isset($start)&&$start=="")
            {
                $map['pay_time'] = ['<= time',$end];
            }
            if(isset($start)&&$start!=""&&isset($end)&&$end!="")
            {
                $map['pay_time'] = ['between time',[$start,$end]];
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'o.*,school_erp,school_name,user_gender,uson_username,uson_parent_phone';
            $count = Db::table('up_self_order')->alias('o')
                ->join('up_school s','o.order_school=s.school_erp','LEFT')
                ->join('up_u_user_son us','o.order_user_son_id=us.uson_id','LEFT')
                ->where($map)
                ->count();// 获取总条数
            $lists = Db::table('up_self_order')->alias('o')
                ->join('up_school s','o.order_school=s.school_erp','LEFT')
                ->join('up_u_user_son us','o.order_user_son_id=us.uson_id','LEFT')
                ->where($map)
                ->order('is_pay ASC,is_send ASC,created_at ASC')
                ->page($Nowpage,$limits)
                ->field($field)
                ->select();
            if($lists){
                foreach ($lists as $k => $v){
                    $lists[$k]['can_send'] = 1; //不能发货了
                    $have = Db::table('up_self_order_detail')
                        ->where('order_id', $v['order_id'])
//                        ->where('detail_express_no',[['eq',null],['eq','']],'OR')
                        ->where('detail_express_no',null)
                        ->find();
                    if($have){
                        $lists[$k]['can_send'] = 2; //还要发货
                    }
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $schools = Db::table('up_tg_school ts')
            ->join('up_school s','ts.ts_school_erp=s.school_erp','LEFT')
            ->group('ts_school_erp')
            ->field('school_name,school_erp')
            ->select();
        $this->assign('schools',$schools);
        return $this->fetch('orderps/index');
    }
    /**
     * 发货
     */
    public function orderSend(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            if(empty($fahuo)){
                return json(['code'=>100,'msg'=>'选择不能为空']);
            }
            Db::startTrans();
            try {
                $param = [
                    'detail_express' => $express,
                    'detail_express_no' => $express_no,
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                $deids = implode($fahuo, ',');
                Db::table('up_self_order_detail')
                    ->where('order_id', $order_id)
                    ->where('tg_type', 'in', $deids)
                    ->update($param);
                Db::table('up_self_order')
                    ->where('order_id', $order_id)
                    ->update([
                        'is_send' => 1,
                        'send_time' => date('Y-m-d H:i:s')
                    ]);
                Db::commit();
                return json(['code' => 200, 'msg' => '成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        $field = 'detail_id,tg_type,attr_id,count(*) num,detail_express,detail_express_no';
        $details = Db::table('up_self_order_detail')
            ->where('order_id',$order_id)
            ->group('tg_type')
            ->order('tg_type')
            ->field($field)
            ->select();
        $t_names = $this->t_names;
        return $this->fetch('orderps/ordersend',['data'=>$order,'details'=>$details,'t_names'=>$t_names]);
    }
    /**
     * 修改物流地址
     */
    public function orderUpdateSend(){
        extract(input());
        if(Request::instance()->isPost()){
            extract(input());
            if(empty($fahuo)){
                return json(['code'=>100,'msg'=>'选择不能为空']);
            }
            Db::startTrans();
            try {
                $param = [
                    'detail_express' => $express,
                    'detail_express_no' => $express_no,
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
                $deids = implode($fahuo, ',');
                Db::table('up_self_order_detail')
                    ->where('order_id', $order_id)
                    ->where('tg_type', 'in', $deids)
                    ->update($param);
                Db::commit();
                return json(['code' => 200, 'msg' => '成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $order = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->find();
        $field = 'detail_id,tg_type,attr_id,count(*) num,detail_express,detail_express_no';
        $details = Db::table('up_self_order_detail')
            ->where('order_id',$order_id)
            ->group('tg_type')
            ->order('tg_type')
            ->field($field)
            ->select();
        $t_names = $this->t_names;
        return $this->fetch('orderps/ordersend_edit',['data'=>$order,'details'=>$details,'t_names'=>$t_names]);
    }



    /**
     * 删除订单
     * @return \think\response\Json
     */
    public function orderDel(){
        $order_id = input('id');
        $res = Db::table('up_self_order')
            ->where('order_id',$order_id)
            ->setField('is_delete',1);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }



    /**
     * 订单详情
     */
    public function orderInfo(){
        $order_id = input('order_id');
        $field = 'o.*,user_username,uson_idcard,uson_username,uson_parent_phone';
        $order = Db::table('up_self_order')->alias('o')
            ->join('up_u_user u','o.user_id=u.user_id','LEFT')
            ->join('up_u_user_son us','o.order_user_son_id=us.uson_id','LEFT')
            ->where('order_id',$order_id)
            ->field($field)
            ->find();
        $where = [
            'od.order_id' => $order_id
        ];
        $field = 'tg_type,attr_id,th_status,refund_status,count(*) num,sum(unit_price) price,detail_express,detail_express_no';
        $field .= ',tui.status,tui.is_send,tui.merchant_remark,tui.merchant_express,tui.merchant_express_no,tui.express_no';
        $field .= ',tui.erp_new_size,tui.remark,tui.pic_list';
        $data = Db::table('up_self_order_detail od')
            ->join('up_self_order_tui tui','od.detail_id=tui.order_detail_id','LEFT')
            ->where($where)
            ->group('tg_type')
            ->order('tg_type')
            ->field($field)
            ->select();
        foreach ($data as $k => $v){
            if($v['pic_list']){
                $data[$k]['pic_list'] = explode(',',$v['pic_list']);
            }
            $data[$k]['goods'] = Db::table('up_self_order_detail od')
                ->join('up_goods g','od.goods_id=g.good_id','LEFT')
                ->where($where)
                ->where('tg_type',$v['tg_type'])
                ->field('good_name,good_coding,unit_price,num')
                ->select();
        }
        $t_names = $this->t_names;
        return $this->fetch('orderps/orderinfo',['data'=>$order,'taos'=>$data,'t_names'=>$t_names]);
    }

    /**
     * 查看物流列表
     * @return mixed|\think\response\Json
     */
    public function orderWuliu(){
        if(request()->isAjax()){
            extract(input());
            $order_id = input('order_id');
            $where = [
                'order_id' => $order_id
            ];
            $count = Db::table('up_self_order_detail')
                ->where($where)
                ->group('tg_type')
                ->count();// 获取总条数
            $field = 'detail_id,tg_type,attr_id,count(*) num,detail_express,detail_express_no';
            $lists = Db::table('up_self_order_detail')
                ->where($where)
                ->group('tg_type')
                ->order('tg_type')
                ->field($field)
                ->select();
            $t_names = $this->t_names;
            foreach ($lists as $k => $v){
                $lists[$k]['name'] = $t_names[$v['tg_type']];
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $order_id = input('order_id');
        $this->assign('order_id',$order_id);
        return $this->fetch('orderps/wuliu');
    }
    /**
     * 查看物流详情
     * @return mixed|\think\response\Json
     */
    public function wuliuInfo(){
        $code = input('express_no');
        $info = orderWuLiu($code);
        $this->assign('info',$info);
        return $this->fetch('orderps/wuliuinfo');
    }
    /**
     * 导入物流Excel
     * @return mixed
     */
    public function excelIn(){
        set_time_limit(0);
        if(request()->file('file')){
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            $time = date('Y-m-d H:i:s');
            $data = [];
            Db::startTrans();
            try {
                for ($i=2;$i<=$highestRow;$i++) {
                    $a = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue (); //
                    $b = $objPHPExcel->getActiveSheet ()->getCell ("B" . $i)->getValue (); //
                    $c = $objPHPExcel->getActiveSheet ()->getCell ("C" . $i)->getValue (); //
                    $d = $objPHPExcel->getActiveSheet ()->getCell ("D" . $i)->getValue (); //
                    if($a != '' && $b != '' && $d != ''){
                        $order_id = Db::table('up_self_order')->where('order_no', $a)->value('order_id');
                        $param = [
                            'detail_express' => $c,
                            'detail_express_no' => $d,
                            'updated_at' => $time
                        ];
                        Db::table('up_self_order_detail')
                            ->where('order_id', $order_id)
                            ->where('tg_type', $b)
                            ->update($param);
                        Db::table('up_self_order')
                            ->where('order_id', $order_id)
                            ->update([
                                'is_send' => 1,
                                'send_time' => $time
                            ]);
                    }
                }
                Db::commit();
                echo '/admin/orderps/index';
            } catch (\Exception $e) {
                Db::rollback();
                echo '/admin/orderps/excelIn';
            }
        }
        return $this->fetch('orderps/excelin');
    }
    //导出
    public function excelOutOrder()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['o.is_delete'] = 0;
        $map['order_contract'] = 3;
        $map['is_pay'] = 1;
        if(isset($n_title)&&$n_title!="")
        {
            $map['order_no|name|mobile'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($contract)&&$contract!="")
        {
            $map['order_contract'] = $contract;
        }
        if(isset($schoolid)&&$schoolid!="")
        {
            $map['order_school'] = $schoolid;
        }
        if(isset($order_erp_year)&&$order_erp_year!="")
        {
            $map['order_erp_year'] = $order_erp_year;
        }
        if(isset($type) && $type){
            if($type == 2){
                $map['is_send'] = 0;
            }
            if($type == 3){
                $map['is_send'] = 1;
            }
            if($type == 4){
                $map['is_send'] = 2;
            }
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end=="")
        {
            $map['pay_time'] = ['>= time',$start];
        }
        if(isset($end)&&$end!=""&&isset($start)&&$start=="")
        {
            $map['pay_time'] = ['<= time',$end];
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end!="")
        {
            $map['pay_time'] = ['between time',[$start,$end]];
        }
        $field = [
            'o.pay_time','order_no','school_name','uson_class','uson_username',
            'o.all_good_nums','all_goods_price','o.total_price','is_pay','mobile',
            'o.address','order_back_order_id','o.remark'
        ];
        $data = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son u','o.order_user_son_id=u.uson_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->where($map)
            // ->field($field)
            ->count();
        if($data > 0){
            $cellname = [
                '付款日期', '订单编号', '学校', '班级', '学生名称',
                '总数量', '总销售金额', '总金额', '支付状态', '收件电话', '收件地址',
                '付款流水', '备注'
            ];
//            $status = ['is_pay','pay_type','is_send','order_contract','order_cancel_status','order_cancel_pay','new_old'];
//            $values = [
//                 'is_pay' => [0 => '待支付',1 => '已支付',2 => '已取消']
//                ,'pay_type' => [1 => '微信',2 => '支付宝',3 => '银联']
//                ,'is_send' => [0 => '未发货',1 => '已发货待收货',2 => '已收货待评价',3 => '已完成']
//                ,'order_contract' => [1 => '自营订单',2 => '增补订单']
//                ,'order_cancel_status' => [1 => '未取消',2 => '取消被拒',3 => '已同意取消',4 => '待审核']
//                ,'order_cancel_pay' => [1 => '正常',2 => '未打款',3 => '已打款']
//                ,'new_old' => [1 => '新APP订单',2 => '旧APP订单']
//            ];
            $status = ['is_pay'];
            $values = [
                'is_pay' => [0 => '未付款',1 => '已付款',2 => '已取消']
            ];
            $res = exportExcelOrder('order',time(),$cellname,$data,$status,$values,1,ceil($data/10000),$map,$field);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
    //导出明细
    public function excelOutDetail()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $map = [];
        $map['o.is_delete'] = 0;
        $map['order_contract'] = 3;
        $map['is_pay'] = 1;
        if(isset($n_title)&&$n_title!="")
        {
            $map['order_no|name|mobile'] = ['like',"%" . $n_title . "%"];
        }
        if(isset($contract)&&$contract!="")
        {
            $map['order_contract'] = $contract;
        }
        if(isset($schoolid)&&$schoolid!="")
        {
            $map['order_school'] = $schoolid;
        }
        if(isset($order_erp_year)&&$order_erp_year!="")
        {
            $map['order_erp_year'] = $order_erp_year;
        }
        if(isset($type) && $type){
            if($type == 2){
                $map['is_send'] = 0;
            }
            if($type == 3){
                $map['is_send'] = 1;
            }
            if($type == 4){
                $map['is_send'] = 2;
            }
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end=="")
        {
            $map['pay_time'] = ['>= time',$start];
        }
        if(isset($end)&&$end!=""&&isset($start)&&$start=="")
        {
            $map['pay_time'] = ['<= time',$end];
        }
        if(isset($start)&&$start!=""&&isset($end)&&$end!="")
        {
            $map['pay_time'] = ['between time',[$start,$end]];
        }
        $field = [
            'o.order_no','order_back_order_id','school_name','o.pay_time',
            'tg_type','good_name','good_coding','attr_id','num',
            'unit_price','unit_price*num unit_all_price','uson_username','user_gender','order_erp_year','uson_grade',
            'uson_class','order_erp_done','name','mobile','address'
        ];
        $data = Db::table('up_self_order')->alias('o')
            ->join('up_self_order_detail od','o.order_id=od.order_id','LEFT')
            ->join('up_goods g','od.goods_id=g.good_id','LEFT')
            ->join('up_u_user_son u','o.order_user_son_id=u.uson_id','LEFT')
            ->join('up_school s','o.order_school=s.school_erp','LEFT')
            ->where($map)
            ->count();
        if($data > 0){
            $cellname = [
                '订单编号', '付款流水', '学校名称','付款日期',
                '品类', '商品名称', '款号', '尺码', '数量',
                '单价','合计金额', '学生姓名', '性别', '入学年份', '年级',
                '班级', '订单交期', '收件人', '收件电话','收件地址'
            ];
            $status = ['tg_type','user_gender'];
            $values = [
                'tg_type' => [1 => '夏服',2 => '秋服',3 => '礼服',4 => '冬装',5 => '西服'],
                'user_gender' => [1 => '男',2 => '女']
            ];
            $res = exportExcelOrder('tongorderinfo',time(),$cellname,$data,$status,$values,2,ceil($data/10000),$map,$field);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}